package cn.bx.bid.ctrl;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


//拦截器
@Service("interceptor")
public class Interceptor implements HandlerInterceptor {
    //返回true,放行
    //返回false,终止执行
    @Override//控制器执行之前执行
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("拦截了："+o+"对象,,,,,,,,,,,,,,,,,,,,,"+o.getClass().getName());

        //String path=httpServletRequest.getServletPath();
        long start = System.nanoTime();
        httpServletRequest.setAttribute("time",start);
        Object user=httpServletRequest.getSession().getAttribute("USER_LOGIN");
        if(user==null) {
            //转发
            httpServletRequest.setAttribute("msg","没有权限访问！");
            httpServletRequest.getRequestDispatcher("/login.jsp").forward(httpServletRequest,httpServletResponse);
            return false;
        }
        return true;
    }

    @Override//控制器执行完成后，视图处理之前 执行
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("视图名称："+modelAndView.getViewName()+",数据有："+modelAndView.getModelMap());
        long end = System.nanoTime();
        Object ol  = httpServletRequest.getAttribute("time");
        long start = Long.valueOf(String.valueOf(ol));
        System.out.println("拦截"+o+"耗时"+(end-start)+"s");
    }

    @Override//视图处理完成后执行
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("视图解析完成");

    }
}
